package com.xzy.spring.demo.proxy.auto.cglib;

import com.xzy.spring.demo.proxy.RealSubject;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author xzy
 * @date 2021/3/11 22:08
 * 说明：CGLig动态代理
 */
public class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        // 附加的代理逻辑
        System.out.println(">>>开始执行");

        // 目标方法
        Object o1 = methodProxy.invokeSuper(o, args);

        // 附加的代理逻辑
        System.out.println(">>>执行结束");
        return null;
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        // 设置目标类
        enhancer.setSuperclass(RealSubject.class);
        // 设置回调方法
        enhancer.setCallback(new MyMethodInterceptor());

        RealSubject proxyRealSubject = (RealSubject) enhancer.create();
        proxyRealSubject.request();
        System.out.println(proxyRealSubject.getClass());
    }
}
